#include "AgentService.h"
#include <cstdio>
#include <cstring>


int AgentService::connect()
{
	conn.connectToService(AGENT_IP, AGENT_PORT);
	return 1;
}

std::string AgentService::getInputPath()
{
	char mess[AGENT_MESS_LEN];
	std::string result;
	conn.TcpRecv(mess, AGENT_MESS_LEN);
	result = mess;
	return result;
}

double AgentService::getCGRatio()
{
	char mess[AGENT_MESS_LEN];
	double result;
	conn.TcpRecv(mess, AGENT_MESS_LEN);
	sscanf(mess, "%lf", &result);
	return result;
}

std::vector<struct keyValue> AgentService::getKeyValue()
{
	char mess[AGENT_MESS_LEN];
	std::vector<struct keyValue> result;
	struct keyValue tmp;
	int total, i;
	conn.TcpRecv(mess, AGENT_MESS_LEN);
	sscanf(mess, "total %d", &total);
	for (i=0;i<total;i++) {
		conn.TcpRecv(mess, AGENT_MESS_LEN);
		sscanf(mess, "%d %d", &tmp.key, &tmp.value);
		result.push_back(tmp);
	}
	return result;
}

int AgentService::uploadResults(char *buf, int len)
{
	char mess[AGENT_MESS_LEN];
	int i = 0;
	sprintf(mess, "data %d", len);
	conn.TcpSend(mess, AGENT_MESS_LEN);
	while (i < len) {
		if (i + AGENT_MESS_LEN >= len) {
			for (;i<len;i++)
				mess[i%AGENT_MESS_LEN] = buf[i];
		} else {
			memcpy(mess, buf+i, AGENT_MESS_LEN);
			i += AGENT_MESS_LEN;
		}
		conn.TcpSend(mess, AGENT_MESS_LEN);
	}
	conn.closeService();
	return 1;
}
